var express = require('express')
var router = express.Router()
var multer = require('multer')

var storage = multer.diskStorage({

  // 将上传的文件存储在指定的位置（不存在的话需要手动创建）
  destination: function (req, file, cb) {
    cb(null, './static/uploads')
  },
  // 将上传的文件做名称的更改
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname)
  }
})

// 创建multer对象
var upload = multer({ storage: storage })

router.post('/upload', upload.single('imgpath'), (req, res) => {
  console.log(req.file)
  const {size, mimetype, filename} = req.file
  const type = ['jpg', 'png', 'jpeg', 'timg']
  const tnType = mimetype.split('/')[1]
  if (size > 50000000) {
    res.send({mas: '尺寸过大！', status: 0})
  } else if (size < 10000) {
    res.send({mas: '尺寸过小！', status: 0})
  } else if (!type.includes(tnType)) {
    res.send({mas: '上传文件类型错误！', status: 0})
  } else {
    const img = `public/uploads/${filename}`
    res.send({mas: '上传成功！', status: 1, img})
  }
})
// 导出模块
module.exports = router
